//
//  AddCompanyTableViewController.m
//  帮惠Mall
//
//  Created by reew on 2017/9/20.
//  Copyright © 2017年 reew. All rights reserved.
//

#import "AddCompanyTableViewController.h"
#import "CommonUtils.h"
#import <AFNetworking.h>
#import "User.h"
#import <SVProgressHUD.h>
#import <QBImagePickerController/QBImagePickerController.h>
#import "ImageCollectionViewCell.h"
#import "TagImgeViewController.h"
#import "System.h"
@interface AddCompanyTableViewController ()<QBImagePickerControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UITableViewCell *pickerCell;

@property (nonatomic,strong) QBImagePickerController *imagePicker;

@property (nonatomic, assign) CGFloat collectionFrameY;
@property (nonatomic,strong) NSMutableArray *imageArr;
//大图image 数组
@property(nonatomic,strong) NSMutableArray * bigImageArray;
//选择的图片数据
@property(nonatomic,strong) NSMutableArray *arrSelected;
@property (nonatomic,strong) UICollectionView *pickerCollectionView;
@end

@implementation AddCompanyTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
//    self.title = @"企业认证";
    _imageArr = [NSMutableArray array];
    //添加手势 点击页面隐藏键盘
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [self.tableView addGestureRecognizer:tapGestureRecognizer];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];;
    //初始化照片选择器
    _imagePicker = [QBImagePickerController new];
    _imagePicker.delegate = self;
    _imagePicker.allowsMultipleSelection = YES;
    _imagePicker.maximumNumberOfSelection = 7;
    _imagePicker.prompt = @"选择图片";
    [self initPickerCollectionView];
   
}
#pragma mark - 私有方法
- (void)checkInfo{
    if (_imageArr.count == 0){
        [SVProgressHUD setMaximumDismissTimeInterval:0.5];
        [SVProgressHUD showErrorWithStatus:@"请选择图片"];
    }
    else{
        [self sendRequest];
    }
}
- (void)sendRequest{
    
    if ([self.skipType isEqualToString:@"uploadGoodsImage"]) {
        [self uploadGoodsImage];
    }else{
//        [self addCompany];
    }
}

- (void)uploadGoodsImage{
    [CommonUtils showHudWithStatus:LoadingStatus stayTime:1 info:nil];
    NSString *url = [kBaseURL stringByAppendingPathComponent:kAdd_goods_img];
    
    AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //参数必选：goodsNo（商品编号）ile（上传图片 支持多张上传）
        //   主图名称为master.jpg|jpeg，其他图片名称自定义
        
        if (!(_goodsNo == nil)) {
            [formData appendPartWithFormData:[_goodsNo dataUsingEncoding:NSUTF8StringEncoding] name:@"goodsNo"];
        }
        for (int i = 0; i<_imageArr.count; i++) {
            UIImage *img = _imageArr[i];
            NSData *imgData = UIImageJPEGRepresentation(img, 0.05);
            if (i==0) {
                [formData appendPartWithFileData:imgData name:@"file" fileName:@"master.png" mimeType:@"image/png"];
            }else{
                [formData appendPartWithFileData:imgData name:@"file" fileName:@"ios.png" mimeType:@"image/png"];
            }
        }

    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSNumber *result = responseObject[@"result"];
        NSString *message = responseObject[@"message"];
        [CommonUtils showHudWithStatus:SuccessStatus stayTime:1 info:message];
        if ([result integerValue] == 1) {
            //成功
            UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            TagImgeViewController *vc = [sb instantiateViewControllerWithIdentifier:@"tagImage"];
            vc.goodsNo = _goodsNo;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [CommonUtils showHudWithStatus:ErrorStatus stayTime:1 info:@"网络请求错误"];
    }];
}
- (void)uploadSizeImage{
    
}
//初始化colectionView
- (void)initPickerCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _pickerCollectionView.alpha = 0;
    _pickerCollectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    [_pickerCell addSubview:_pickerCollectionView];
    
    self.pickerCollectionView.delegate=self;
    self.pickerCollectionView.dataSource=self;
    self.pickerCollectionView.backgroundColor = [UIColor whiteColor];
    _pickerCollectionView.scrollEnabled = NO;
    
    if(_imageArr.count == 0)
    {
        _imageArr = [NSMutableArray array];
    }
    if(_bigImageArray.count == 0)
    {
        _bigImageArray = [NSMutableArray array];
    }
    if(_arrSelected.count == 0){
        _arrSelected = [NSMutableArray array];
    }
}
#pragma mark - <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imageArr.count+1;
//    return 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UINib *nib = [UINib nibWithNibName:@"ImageCollectionViewCell" bundle: [NSBundle mainBundle]];
    [collectionView registerNib:nib forCellWithReuseIdentifier:@"LCCollectionViewCell"];
    ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"LCCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.row == _imageArr.count) {
        cell.profilePhoto.image = [UIImage imageNamed:@"ic_addphotos"];
        cell.closeButton.hidden = YES;
    }else{
        [cell.profilePhoto setImage:_imageArr[indexPath.item]];
        cell.closeButton.hidden = NO;
    }
    if (_isShowDefault) {
        if (indexPath.row == 0) {
            cell.defaultBtn.hidden = NO;
        }else{
            cell.defaultBtn.hidden = YES;
        }
    }else{
        cell.defaultBtn.hidden = YES;
    }
    cell.profilePhoto.tag = [indexPath item];
    //添加图片cell点击事件
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapProfileImage:)];
    singleTap.numberOfTapsRequired = 1;
    cell.profilePhoto .userInteractionEnabled = YES;
    [cell.profilePhoto  addGestureRecognizer:singleTap];
    cell.closeButton.tag = [indexPath item];
    [cell.closeButton addTarget:self action:@selector(deletePhoto:) forControlEvents:UIControlEventTouchUpInside];
    [self changeCollectionViewHeight];
    return cell;
}
#pragma mark <UICollectionViewDelegate>
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(([UIScreen mainScreen].bounds.size.width-64) /4 ,([UIScreen mainScreen].bounds.size.width-64) /4+20);
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 8, 10, 8);
}
#pragma mark - 图片cell点击事件
//点击图片看大图
- (void) tapProfileImage:(UITapGestureRecognizer *)gestureRecognizer{
    [self.view endEditing:YES];
    
    UIImageView *tableGridImage = (UIImageView*)gestureRecognizer.view;
    NSInteger index = tableGridImage.tag;
    
    if (index == (_imageArr.count)) {
        [self.view endEditing:YES];
        //添加新图片
        [self addNewImg];
    }

}
- (void)addNewImg{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *Ac1 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self presentViewController:_imagePicker animated:YES completion:nil];
    }];
//    UIAlertAction *Ac2 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:Ac1];
//    [alertVc addAction:Ac2];
    [alertVc addAction:cancle];
    [self presentViewController:alertVc animated:YES completion:nil];
}
- (void)deletePhoto:(UIButton *)sender{
    
    [_imageArr removeObjectAtIndex:sender.tag];
    [_arrSelected removeObjectAtIndex:sender.tag];
    [_imagePicker.selectedAssets removeObjectAtIndex:sender.tag];
    
    [self.pickerCollectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:sender.tag inSection:0]]];
    
    for (NSInteger item = sender.tag; item <= _imageArr.count; item++) {
        ImageCollectionViewCell *cell = (ImageCollectionViewCell*)[self.pickerCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0]];
        cell.closeButton.tag--;
        cell.profilePhoto.tag--;
        
        
    }
    
    [self changeCollectionViewHeight];
}
- (void)changeCollectionViewHeight{
    
//    if (_collectionFrameY) {
//        _pickerCollectionView.frame = CGRectMake(0, _collectionFrameY, [UIScreen mainScreen].bounds.size.width, (((float)[UIScreen mainScreen].bounds.size.width-64.0) /4.0 +20.0)* ((int)(_arrSelected.count)/4 +1)+20.0);
//    }
//    else{
//        _pickerCollectionView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, (((float)[UIScreen mainScreen].bounds.size.width-64.0) /4.0 +20.0)* ((int)(_arrSelected.count)/4 +1)+20.0);
//    }
    _pickerCollectionView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, (((float)[UIScreen mainScreen].bounds.size.width-64.0) /4.0 +20.0+20)* ((int)(_arrSelected.count)/4 +1)+20.0);
    [self pickerViewFrameChanged];
    
}
- (void)pickerViewFrameChanged{
//    _pickerCell.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, (((float)[UIScreen mainScreen].bounds.size.width-64.0) /4.0 +20.0)* ((int)(_arrSelected.count)/4 +1)+20.0);
//    _pickerCollectionView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, (((float)[UIScreen mainScreen].bounds.size.width-64.0) /4.0 +20.0)* ((int)(_arrSelected.count)/4 +1)+20.0);
}
- (void)updatePickerViewFrameY:(CGFloat)Y{
    
    _collectionFrameY = Y;
    _pickerCollectionView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, (((float)[UIScreen mainScreen].bounds.size.width-64.0) /4.0 +20.0+20)* ((int)(_arrSelected.count)/4 +1)+20.0);
}
- (IBAction)selectImage:(UIButton *)sender {
    
}
#pragma mark - QBImagePickerController
-(void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets{
    _arrSelected = [NSMutableArray array];
    _imageArr = [NSMutableArray array];
    for (PHAsset *set in assets) {
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        
        [[PHImageManager defaultManager] requestImageForAsset:set targetSize:[UIScreen mainScreen].bounds.size contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
            //设置图片
            [self.arrSelected addObject:result];
            [self.imageArr addObject:result];
            [_pickerCollectionView reloadData];
        }];
    }

    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
-(void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)hideKeyBoard{
    [self.tableView endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)submit:(UIButton *)sender {
    [self checkInfo];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 25;
}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
